package com.loong.service.impl;

import com.loong.mapper.UserMapper;
import com.loong.mapper.impl.UserMapperImpl;
import com.loong.pojo.User;
import com.loong.service.UserService;
import com.loong.utils.Constants;
import com.loong.utils.EmailUtils;
import com.loong.utils.MD5Utils;


public class UserServiceImpl implements UserService {

    @Override
    public boolean checkedUser(String username) {
        UserMapper userMapper = new UserMapperImpl();
        User user = userMapper.selectUserByUsername(username);
        return user != null;
    }

    @Override
    public int registerUser(User user){
        //用户保存到数据库
        UserMapper userMapper = new UserMapperImpl();
        int i = userMapper.insertUser(user);
        //发送邮件
        EmailUtils.sendEmail(user);
        return i;
    }

    @Override
    public int activeUser(String code) {
        UserMapper userMapper = new UserMapperImpl();
        //根据激活码查找用户
        User user = userMapper.selectUserByCode(code);
        if(user == null){
            return Constants.ACTIVE_FAIL;//激活失败
        }
        if(user.getStatus() == Constants.USER_ACTIVE){
            return Constants.ACTIVE_ALREADY;//已经激活
        }
        //进行激活操作
        int i = userMapper.updateUserStatusByUid(user.getUid());
        if(i > 0){
            return Constants.ACTIVE_SUCCESS;
        }
        return Constants.ACTIVE_FAIL;
    }

    @Override
    public User login(String username, String password) {
//        1.需要将密码进行MD5处理
        String md5password = MD5Utils.md5(password);
        UserMapper userMapper = new UserMapperImpl();
        User user = userMapper.selectUserByUsername(username);
        if(user != null && user.getPassword().equals(md5password)){
            return user;
        }
        return null;
    }
}
